//
//  ZFUserAccount.swift
//  WeiBo
//
//  Created by 左忠飞 on 2016/12/28.
//  Copyright © 2016年 左忠飞. All rights reserved.
//

import UIKit

fileprivate let accountFile:NSString = "useraccount.json"

///用户账户信息
class ZFUserAccount: NSObject {

    //访问令牌
    var access_token:String?// = "2.00p68gOEaMdKmC70541609aezWOFcD"
    
    //用户代号
    var uid : String?
    
    //accesstoken 的声明周期
    //过期日期,单位:秒,
    //开发者5年,每次登陆都是5年
    //使用者3天,会从第一次登陆开始递减
    var expires_in:TimeInterval = 0 {
        didSet {
            expiresDate = Date(timeIntervalSinceNow: expires_in)
        }
    }
    
    //过期日期
    var expiresDate:Date?
    
    //用户昵称
    var screen_name:String?
    //用户头像
    var avatar_large:String?
    
    
    
    override var description: String {
        return yy_modelDescription()
    }
    
    override init() {
        super.init()
        //从磁盘加载保存的文件 -> 得到字典
        //从磁盘文件中加载出二进制数据,如果失败直接返回
        guard let path = accountFile.cz_appendDocumentDir(),
        let data = NSData(contentsOfFile: path),
        let dict = try? JSONSerialization.jsonObject(with: data as Data, options: []) as? [String:AnyObject]
            else{
                return
        }
        
        
        //使用字典设置属性值
        //用户是否登录的关键代码
        self.yy_modelSet(with: dict ?? [:])
        
        //测试 token 过期,在开发中,每一个分之都要处理
        //expiresDate = Date(timeIntervalSinceNow: -3600 * 3600)

        //判断 token 是否过期
        if expiresDate?.compare(Date()) != .orderedDescending {
            
            print("账户过期")
            //清空 token
            access_token = nil
            uid = nil
            
            //删除沙盒中的账户文件
            _ = try? FileManager.default.removeItem(atPath: path)
        }
    }
    
    
    /**
     1偏好设置(小的)
     2沙盒-归档/plist/json
     3数据库(FMDB/coreData)
     4钥匙串访问(小的/自动加密/需要使用框架 SSKeyChain)
    */
    func saveAccount() {
        
        //模型转字典,需要删除 expires_in
        var dict = (self.yy_modelToJSONObject() as? [String:AnyObject]) ?? [:]
        dict.removeValue(forKey: "expires_in")
        //字典序列化
        guard let data = try? JSONSerialization.data(withJSONObject: dict, options: []),
        let filePath = (accountFile).cz_appendDocumentDir()
            else {
            return
        }
        print("用户账户文件保存地址")
        //写入磁盘
        (data as NSData).write(toFile: filePath, atomically: true)
        
        print("用户账户保存成功,\(filePath)")
        
    }
    
}
